package cn.com.lyj6851.auth.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class AuthSecurityConfig extends WebSecurityConfigurerAdapter {

	// 注入自定义的用户获取
    @Autowired
    private UserDetailsService userDetailsService;

    @Bean
    public PasswordEncoder passwordEncoder(){ 
        return PasswordEncoderFactories.createDelegatingPasswordEncoder();
    }

    @Override
	@Bean
	public AuthenticationManager authenticationManagerBean() throws Exception {
		return super.authenticationManagerBean();
	}
    
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService)// 使用自定义认证用户信息
             .passwordEncoder(passwordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
    	http.formLogin()
    	    .loginPage("/authentication/require")
	        .loginProcessingUrl("/authentication/form")
	        .and()
	        .authorizeRequests()
	        .antMatchers("/authentication/require",
	                "/authentication/form",

	                "/**/*.js",
                    "/**/*.css",
                    "/**/*.jpg",
                    "/**/*.png",
                    "/**/*.woff2"
	        		).permitAll()
	        .anyRequest().authenticated()
	        .and()
	        .csrf().disable();
    	
    	//http.httpBasic();
    }
    
}